import pygame
import random
import time
import image
from settings import *


class Bee:
    def __init__(self):
        # Set random size for the bee
        random_size_value = random.uniform(MOSQUITO_SIZE_RANDOMIZE[0], MOSQUITO_SIZE_RANDOMIZE[1])
        size = (int(MOSQUITOS_SIZES[0] * random_size_value), int(MOSQUITOS_SIZES[1] * random_size_value))

        # Define movement and spawn position of the bee
        moving_direction, start_pos = self.define_spawn_pos(size)

        # Create the rect object for collision detection
        self.rect = pygame.Rect(start_pos[0], start_pos[1], size[0] // 1.4, size[1] // 1.4)

        # Load the bee sprite(s)
        self.images = [image.load("assets/bee/bee.png", size=size, flip=moving_direction == "right")]

        self.current_frame = 0
        self.animation_timer = 0

    def define_spawn_pos(self, size):
        # Random spawn and movement for the bee
        vel = random.uniform(MOSQUITOS_MOVE_SPEED["min"], MOSQUITOS_MOVE_SPEED["max"])
        moving_direction = random.choice(("left", "right", "up", "down"))

        if moving_direction == "right":
            start_pos = (-size[0], random.randint(size[1], SCREEN_HEIGHT - size[1]))
            self.vel = [vel, 0]
        elif moving_direction == "left":
            start_pos = (SCREEN_WIDTH + size[0], random.randint(size[1], SCREEN_HEIGHT - size[1]))
            self.vel = [-vel, 0]
        elif moving_direction == "up":
            start_pos = (random.randint(size[0], SCREEN_WIDTH - size[0]), SCREEN_HEIGHT + size[1])
            self.vel = [0, -vel]
        elif moving_direction == "down":
            start_pos = (random.randint(size[0], SCREEN_WIDTH - size[0]), -size[1])
            self.vel = [0, vel]

        return moving_direction, start_pos

    def move(self):
        # Update the position of the bee based on its velocity
        self.rect.move_ip(self.vel)

    def animate(self):
        # Update the animation frame of the bee
        t = time.time()
        if t > self.animation_timer:
            self.animation_timer = t + ANIMATION_SPEED
            self.current_frame += 1
            if self.current_frame > len(self.images) - 1:
                self.current_frame = 0

    def draw_hitbox(self, surface):
        # Draw the hitbox for debugging (optional)
        pygame.draw.rect(surface, (200, 60, 0), self.rect)

    def draw(self, surface):
        # Animate and draw the bee sprite
        self.animate()
        image.draw(surface, self.images[self.current_frame], self.rect.center, pos_mode="center")

        if DRAW_HITBOX:
            self.draw_hitbox(surface)

    def kill(self, bees):
        # Remove the bee from the list when killed
        bees.remove(self)
        return -1  # Points for killing the bee (more than a mosquito)